package parking;

import parking.entity.Car;
import parking.entity.Ticket;
import parking.exception.AllParkLotIsFullException;
import parking.exception.BeforeLotUnfullException;
import parking.exception.InvalidTicketException;
import parking.service.IPark;
import parking.service.ParkReport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author daiqing.chen
 */
public class ParkBoy implements IPark,ParkReport {
    /**
     * 所拥有的车场
     */
    protected List<ParkLot> lotList;

    /**
     * 构造器
     * @param parkLots 可变参数
     */
    public ParkBoy(ParkLot... parkLots){
        this.lotList = Arrays.asList(parkLots);
    }

    /**
     * 停车
     *
     * @param car 车
     * @return ticket 停车票
     */
    @Override
    public Ticket park(Car car) {
        Optional<ParkLot> parkLot = findParkLot();
        return parkLot.orElseThrow(AllParkLotIsFullException::new).park(car);
    }

    protected Optional<ParkLot> findParkLot(){
        return lotList.stream().filter(ParkLot::hasSpace).findFirst();
    }
    /**
     * 取车
     *
     * @param ticket 票
     * @return 车
     */
    @Override
    public Car take(Ticket ticket) {
        return this.lotList.stream().filter(n -> n.isValidTicket(ticket)).
                findFirst().orElseThrow(InvalidTicketException::new).take(ticket);
    }

    public List<ParkLot> getLotList() {
        return lotList;
    }

    @Override
    public List<ParkReport> getChildren() {
        return new ArrayList<>(this.lotList);
    }

    @Override
    public String getType() {
        return "B";
    }

    @Override
    public int getHasCar() {
        /*int existCar = 0;
        for (ParkLot p: lotList) {
            existCar = existCar + p.getSpaces().size();
        }*/
        return lotList.stream().mapToInt(parkLot -> parkLot.getSpaces().size()).sum();
    }

    @Override
    public int getTotalSpace() {
        /*int totalSpace = 0;
        for (ParkLot p: lotList) {
            totalSpace = totalSpace + p.capacity;
        }*/
        return lotList.stream().mapToInt(parkLot -> parkLot.capacity).sum();
    }

    /* *//**
     * 获取小弟名下的总车位数
     *
     * @return 总车位数
     *//*
    public int getTotalSpace(){
        int totalSpace = 0;
        for (ParkLot p: lotList) {
            totalSpace = totalSpace + p.getCapacity();
        }
        return totalSpace;
    }

    *//**
     * 已停总车位数
     *
     * @return 已停总车数
     *//*
    public int getExistCar(){
        int existCar = 0;
        for (ParkLot p: lotList) {
            existCar = existCar + p.getSpaces().size();
        }
        return existCar;
    }*/
}
